package com.wk.springboot.util;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

/**
 * @Classname HttpUtil
 * @Description TODO
 * @Date 2019/12/5 14:08
 * @Author by weikai
 */
public class HttpUtil {

  /**
   * 发送文件
   *
   * @param file MultipartEntityBuilder
   */
  public static void sendFileByMultipartEntityBuilder(String url, File file) throws IOException {
    if (file.exists()) {
      //通过HttpClientBuilder构造器创建httpClient
      CloseableHttpClient httpClient = HttpClientBuilder.create().build();
      //设置httpPost参数
      HttpPost httpPost = new HttpPost(url);
      MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

      //把file转为fileBody
      FileBody fileBody = new FileBody(file);

      //解决中文乱码
      multipartEntityBuilder.setMode(HttpMultipartMode.RFC6532);
      multipartEntityBuilder.addPart("files", fileBody);
      HttpEntity httpEntity = multipartEntityBuilder.build();
      httpPost.setEntity(httpEntity);
      httpClient.execute(httpPost);
    }
  }


}
